package reader_;

import org.junit.jupiter.api.Test;

import java.io.FileReader;
import java.io.IOException;

/**
 * @author DCSGO
 * @version 1.0
 * 读取 knowledge.txt 中的数据
 * 并显示到控制台上 使用 FileReader
 */
public class FileReader_ {
    //不同与 FileInputStream 每次读取一个字节的数据
    //FileReader 的读取单位为字符 在读取汉字或其他特殊字符时
    //不再那么容易出现乱码 但它们的方法 却及其相似 几乎只是将 byte 换成了 char

    @Test
    //read() 读取单个字符
    public void read1() {
        String filePath = "C:\\Users\\Administrator\\Desktop\\Javacode\\java-learning-code\\chapter19\\src\\reader_\\knowledge.txt";
        FileReader fileReader = null;
        System.out.println("-------------------read1-----------------");
        try {
            fileReader = new FileReader(filePath);
            int read;
            while ((read = fileReader.read()) != -1) {
                System.out.print((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    //read(char cbuf[]) 读取一组字符
    public void read2() {
        String filePath = "C:\\Users\\Administrator\\Desktop\\Javacode\\java-learning-code\\chapter19\\src\\reader_\\knowledge.txt";
        FileReader fileReader = null;
        System.out.println("-------------------read2-----------------");
        try {
            fileReader = new FileReader(filePath);
            char[] reads = new char[8];
            int readLen;
            while ((readLen = fileReader.read(reads)) != -1) {
                System.out.print(new String(reads, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
